/**
 * User: Baoxu
 * Date: 12-6-26
 * Time: 下午1:12
 */

function prepareSlideshow(){
	var preview = document.getElementById("preview");
	var list = document.getElementById("linklist");
	var links = list.getElementsByTagName("a");
	preview.style.position = "absolute";
	preview.style.marginLeft = "0px";
	preview.style.marginTop = "0px";
	for(var i = 0 ; i < links.length ; i++){
		links[i].onmouseover = function(){
			//闭包内部无法直接引用索引i，使用一个方法在外部获取该索引
			var index = getObjectIndex(links, this);
			//alert(index);
			var m = -((index + 1) * 100)
			moveElement("preview", m, 0, 1)
		}
	}
}

//获取某对象元素在目标数组中的位置索引，如果有，返回索引，没有则返回-1
function getObjectIndex(targetArray, checkObject){
	for(var i = 0 ; i < targetArray.length ; i++){
		if(targetArray[i] == checkObject){
			return i;
		}
	}
	return -1;
}

//移动元素，给出目标元素，目的地坐标以及时间间隔
function moveElement(elementID, final_x, final_y, interval){
	var elem = document.getElementById(elementID);
	var xpos = parseInt(elem.style.marginLeft);
	var ypos = parseInt(elem.style.marginTop);
	var dist = 0;

	if(elem.movement){
		clearTimeout(elem.movement);
	}
	if(xpos == final_x && ypos == final_y){
		return true;
	}
	if(xpos < final_x){
		dist = Math.ceil((final_x - xpos) / 10);
		xpos += dist;
	}
	if(ypos < final_y){
		dist = Math.ceil((final_y - ypos) / 10);
		ypos += dist;
	}
	if(xpos > final_x){
		dist = Math.ceil((xpos - final_x) / 10);
		xpos -= dist;
	}
	if(ypos > final_y){
		dist = Math.ceil((ypos - final_y) / 10);
		ypos-=dist;
	}

	elem.style.marginLeft = xpos + "px";
	elem.style.marginTop = ypos + "px";

	var repeat = "moveElement('" + elementID + "'," + final_x + "," + final_y + "," + interval + ")";
	elem.movement = setTimeout(repeat, interval);
}

//通用函数，将函数加到window的onload列表中
function addOnloadEvent(func){
	var old_onload = window.onload;
	if(typeof(old_onload) != "function"){
		window.onload = func;
	}else{
		window.onload = function(){
			old_onload();
			func();
		}
	}
}

addOnloadEvent(prepareSlideshow);